#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash ITK-5.2.1.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1

yum install -y wget tar environment-modules libatomic

if `wget -t 10 -c -P $buildpath https://github.com/InsightSoftwareConsortium/ITK/releases/download/v5.2.1/InsightToolkit-5.2.1.tar.gz`
then 
   echo "InsightToolkit-5.2.1.tar.gz下载成功!"
else
   echo "InsightToolkit-5.2.1.tar.gz下载失败!"
   echo "即将使用本地目录下的InsightToolkit-5.2.1.tar.gz!"
   src_dir=`pwd`
   cp $src_dir/dependency/src/InsightToolkit-5.2.1.tar.gz $buildpath
fi

set -e
tar xf $buildpath/InsightToolkit-5.2.1.tar.gz -C $buildpath && rm -rf $buildpath/InsightToolkit-5.2.1.tar.gz
cd $buildpath/InsightToolkit-5.2.1
mkdir build
cd build
cmake -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_C_FLAGS_RELEASE=-O0 -DCMAKE_CXX_FLAGS_RELEASE=-O0 -DModule_SimpleITKFilters=ON -DCMAKE_INSTALL_PREFIX=$installpath/ITK-5.2.1/ ../
make -j$(nproc)
make install

cat >$installpath/ITK-5.2.1/ITK_modulefiles<<EOF
#%Module1.0
conflict ITK
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set ITK \$pwd
setenv ITK \$ITK
prepend-path PATH \$ITK/bin
prepend-path LD_LIBRARY_PATH \$ITK/lib
prepend-path CPLUS_INCLUDE_PATH \$ITK/include/ITK-5.2
EOF

rm -rf $buildpath/InsightToolkit-5.2.1